// local-pve-ai.js - 本地PVE对决模式AI逻辑

class LocalPVEAI {
    constructor(game, isSecondAI = false) {
        this.game = game;
        this.difficulty = 'medium'; // 默认中等难度
        this.isSecondAI = isSecondAI; // 标记是否为第二条AI蛇的AI实例
        
        // 根据是否为第二条AI蛇选择正确的蛇对象
        this.aiSnake = isSecondAI ? game.aiSnake2 : game.aiSnake;
        
        // 攻击性行为相关属性
        this.aggressiveMode = false; // 是否处于攻击模式
        this.lastAggressiveTime = 0; // 上次进入攻击模式的时间
        this.aggressiveCooldown = 200; // 攻击模式冷却时间（帧数），减少冷却时间
        this.minLengthForAggressive = 8; // 触发攻击模式的最小长度，改回8格
    }
    
    setDifficulty(difficulty) {
        this.difficulty = difficulty;
    }
    
    // 智能移动决策
    moveAI() {
        const aiHead = this.aiSnake.body[0];
        
        // 挑战模式下实现食物分配通讯机制
        if (this.game.isChallengeMode && this.game.aiSnake2 && this.game.aiSnake2.isAlive) {
            return this.communicatedMove(aiHead);
        }
        
        // 根据难度调整AI行为
    switch(this.difficulty) {
        case 'easy':
            return this.easyMove(aiHead);
        case 'medium':
            return this.mediumMove(aiHead);
        case 'hard':
            return this.hardMove(aiHead);
        case 'extreme':
            return this.hardMove(aiHead); // 极限模式也使用困难计算
        default:
            return this.mediumMove(aiHead);
    }
    }
    
    // 简单难度：基础移动，偶尔向食物移动（原简单难度）
    easyMove(aiHead) {
        if (Math.random() < 0.5) {
            // 50%概率随机移动
            return this.randomMove(aiHead);
        } else {
            // 50%概率向食物移动
            return this.moveTowardsFood(aiHead);
        }
    }
    
    // 中等难度：智能选择优先级最高的食物（距离近的优先，特殊食物优先级更高）
    mediumMove(aiHead) {
        // 挑战模式下检查食物竞争，避免与另一条AI蛇抢同一个食物
        if (this.game.isChallengeMode && this.game.aiSnake2 && this.game.aiSnake2.isAlive) {
            if (this.checkFoodCompetition()) {
                // 如果正在抢同一个食物，有50%概率选择其他食物
                if (Math.random() < 0.5) {
                    return this.avoidFoodCompetition(aiHead);
                }
            }
        }
        
        // 获取所有可用食物
        const availableFoods = [];
        
        // 普通食物
        if (this.game.food) {
            availableFoods.push({
                type: 'normal',
                position: this.game.food,
                priority: 1,
                distance: this.getDistance(aiHead, this.game.food)
            });
        }
        
        // 金色食物
        if (this.game.goldenFood) {
            availableFoods.push({
                type: 'golden',
                position: this.game.goldenFood,
                priority: 3, // 金色食物优先级更高
                distance: this.getDistance(aiHead, this.game.goldenFood)
            });
        }
        
        // 移动食物（仅在中等难度时存在）
        if (this.game.movingFood) {
            availableFoods.push({
                type: 'moving',
                position: this.game.movingFood,
                priority: 4, // 移动食物优先级最高
                distance: this.getDistance(aiHead, this.game.movingFood)
            });
        }
        
        // 如果没有食物，随机移动
        if (availableFoods.length === 0) {
            return this.randomMove(aiHead);
        }
        
        // 计算每个食物的综合得分（优先级 + 距离因素）
        availableFoods.forEach(food => {
            // 距离越近得分越高（距离越近，得分越高）
            const distanceScore = 10 - Math.min(food.distance, 10);
            
            // 黄色蛇（第一条AI蛇）更偏向高级食物，增加高级食物权重
            const isYellowSnake = !this.isSecondAI;
            let priorityMultiplier = 10;
            
            if (isYellowSnake) {
                // 黄色蛇对高级食物有更高偏好
                if (food.type === 'golden') priorityMultiplier = 15; // 金色食物权重更高
                else if (food.type === 'moving') priorityMultiplier = 20; // 移动食物权重最高
            }
            
            // 综合得分 = 优先级 * 权重 + 距离得分
            food.score = food.priority * priorityMultiplier + distanceScore;
        });
        
        // 按得分排序，选择得分最高的食物
        availableFoods.sort((a, b) => b.score - a.score);
        
        // 尝试向得分最高的食物移动
        for (let i = 0; i < availableFoods.length; i++) {
            const targetFood = availableFoods[i];
            const direction = this.getDirectionToTarget(aiHead, targetFood.position);
            
            if (this.isDirectionSafe(this.aiSnake, direction)) {
                this.aiSnake.direction = direction;
                return;
            }
        }
        
        // 如果所有方向都不安全，使用随机移动
        this.randomMove(aiHead);
    }
    
    // 困难难度：高级策略，包括攻击性围困行为
    hardMove(aiHead) {
        // 检查是否可以进入攻击模式
        this.checkAggressiveMode();
        
        // 如果处于攻击模式，执行攻击性行为
        if (this.aggressiveMode) {
            return this.aggressiveMove(aiHead);
        }
        
        // 优先获取金色食物（如果距离较近）
        if (this.game.goldenFood) {
            const distanceToGolden = this.getDistance(aiHead, this.game.goldenFood);
            const distanceToFood = this.game.food ? this.getDistance(aiHead, this.game.food) : Infinity;
            
            // 如果金色食物更近或距离差不多，优先获取金色食物
            if (distanceToGolden <= distanceToFood + 2) {
                const goldenDirection = this.getDirectionToTarget(aiHead, this.game.goldenFood);
                if (this.isDirectionSafe(this.aiSnake, goldenDirection)) {
                    this.aiSnake.direction = goldenDirection;
                    return;
                }
            }
        }
        
        // 尝试设置陷阱（当玩家距离较近时）
        const playerHead = this.game.playerSnake.body[0];
        const distanceToPlayer = this.getDistance(aiHead, playerHead);
        
        if (this.canSetTrap() && distanceToPlayer <= 5) {
            return this.setTrapMove(aiHead);
        }
        
        // 如果玩家距离很近，考虑防御性移动
        if (distanceToPlayer <= 3) {
            return this.defensiveMove(aiHead);
        }
        
        // 向食物移动，考虑更复杂的路径规划
        return this.advancedFoodMove(aiHead);
    }
    
    // 极限挑战难度：终极AI策略，结合所有高级行为
    extremeMove(aiHead) {
        // 如果是第二条AI蛇（红色蛇），增加攻击性，减少防御性
        const isRedSnake = this.isSecondAI;
        
        // 注释掉AI蛇之间的碰撞检测，让红蛇更积极地移动
        // if (this.checkImminentCollisionWithOtherAI(aiHead)) {
        //     return this.avoidCollisionMove(aiHead);
        // }
        
        // 检查食物竞争情况，极限挑战下AI更积极争夺食物
        if (this.checkFoodCompetition(aiHead)) {
            // 红色蛇更积极争夺食物，减少避让概率
            if (isRedSnake && Math.random() < 0.3) {
                // 红色蛇有70%概率继续争夺食物
                const competitionMove = this.avoidFoodCompetition(aiHead);
                if (competitionMove) return competitionMove;
            } else if (!isRedSnake && Math.random() < 0.5) {
                // 橙色蛇保持原有避让概率
                const competitionMove = this.avoidFoodCompetition(aiHead);
                if (competitionMove) return competitionMove;
            }
        }
        
        // 红色蛇更频繁尝试攻击性行为
        if (isRedSnake && Math.random() < 0.8) {
            // 红色蛇有80%概率尝试攻击性行为
            const trapMove = this.setTrapMove(aiHead);
            if (trapMove) {
                return trapMove;
            }
            
            // 尝试进入攻击模式
            this.checkAggressiveMode();
            if (this.aggressiveMode) {
                const aggressiveMove = this.aggressiveMove(aiHead);
                if (aggressiveMove) return aggressiveMove;
            }
        } else {
            // 橙色蛇保持原有攻击性
            const trapMove = this.setTrapMove(aiHead);
            if (trapMove) {
                return trapMove;
            }
        }
        
        // 使用高级食物移动策略，更智能地选择食物
        const advancedFoodMove = this.advancedFoodMove(aiHead);
        if (advancedFoodMove) {
            return advancedFoodMove;
        }
        
        // 红色蛇大幅减少防御性移动的使用频率
        if (isRedSnake && Math.random() < 0.2) {
            // 红色蛇只有20%概率使用防御性移动
            return this.defensiveMove(aiHead);
        } else if (!isRedSnake) {
            // 橙色蛇保持原有防御性
            return this.defensiveMove(aiHead);
        }
        
        // 红色蛇如果跳过防御性移动，使用更积极的随机移动
        return this.randomMove(aiHead);
    }
    
    // 随机移动
    randomMove(aiHead) {
        const directions = ['up', 'down', 'left', 'right'];
        const safeDirections = directions.filter(dir => 
            this.isDirectionSafe(this.aiSnake, dir)
        );
        
        if (safeDirections.length > 0) {
            const randomDir = safeDirections[Math.floor(Math.random() * safeDirections.length)];
            this.aiSnake.direction = randomDir;
        }
    }
    
    // 向食物移动
    moveTowardsFood(aiHead) {
        if (this.game.food) {
            const direction = this.getDirectionToTarget(aiHead, this.game.food);
            
            // 检查方向是否安全
            if (this.isDirectionSafe(this.aiSnake, direction)) {
                this.aiSnake.direction = direction;
                return;
            }
        }
        
        // 如果没有安全方向或没有食物，随机移动
        this.randomMove(aiHead);
    }
    
    // 高级食物移动策略
    advancedFoodMove(aiHead) {
        if (!this.game.food) {
            this.randomMove(aiHead);
            return;
        }
        
        // 计算到食物的路径
        const path = this.findPathToFood(aiHead);
        
        if (path && path.length > 1) {
            const nextDirection = this.getDirectionBetween(aiHead, path[1]);
            if (this.isDirectionSafe(this.aiSnake, nextDirection)) {
                this.aiSnake.direction = nextDirection;
                return;
            }
        }
        
        // 如果路径规划失败，使用简单策略
        this.moveTowardsFood(aiHead);
    }
    
    // 设置陷阱移动
    setTrapMove(aiHead) {
        const playerHead = this.game.playerSnake.body[0];
        
        // 预测玩家未来2-3步的位置
        const predictedPositions = this.predictPlayerPositions(2);
        
        // 尝试找到最佳的陷阱位置
        let bestTrapPosition = null;
        let bestScore = -Infinity;
        
        for (const predictedPos of predictedPositions) {
            const trapPosition = this.calculateOptimalTrapPosition(predictedPos);
            if (trapPosition && this.isTrapPositionValid(trapPosition)) {
                const score = this.evaluateTrapPosition(trapPosition, predictedPos);
                if (score > bestScore) {
                    bestScore = score;
                    bestTrapPosition = trapPosition;
                }
            }
        }
        
        if (bestTrapPosition) {
            const trapDirection = this.getDirectionToTarget(aiHead, bestTrapPosition);
            if (this.isDirectionSafe(this.aiSnake, trapDirection)) {
                this.aiSnake.direction = trapDirection;
                return;
            }
        }
        
        // 如果陷阱设置失败，向食物移动
        this.moveTowardsFood(aiHead);
    }
    
    // 获取到目标的方向
    getDirectionToTarget(from, to) {
        const dx = to.x - from.x;
        const dy = to.y - from.y;
        
        if (Math.abs(dx) > Math.abs(dy)) {
            return dx > 0 ? 'right' : 'left';
        } else {
            return dy > 0 ? 'down' : 'up';
        }
    }
    
    // 获取两点之间的方向
    getDirectionBetween(from, to) {
        if (to.x > from.x) return 'right';
        if (to.x < from.x) return 'left';
        if (to.y > from.y) return 'down';
        if (to.y < from.y) return 'up';
        return this.aiSnake.direction; // 默认保持当前方向
    }
    
    // 计算两点之间的曼哈顿距离
    getDistance(pos1, pos2) {
        return Math.abs(pos1.x - pos2.x) + Math.abs(pos1.y - pos2.y);
    }
    
    // 防御性移动：当玩家靠近时，保持安全距离
    defensiveMove(aiHead) {
        const playerHead = this.game.playerSnake.body[0];
        
        // 计算安全方向（远离玩家）
        const safeDirections = ['up', 'down', 'left', 'right'].filter(dir => {
            if (!this.isDirectionSafe(this.aiSnake, dir)) return false;
            
            const newPos = this.getNextPosition(aiHead, dir);
            const newDistance = this.getDistance(newPos, playerHead);
            
            // 选择能增加与玩家距离的方向
            return newDistance > this.getDistance(aiHead, playerHead);
        });
        
        if (safeDirections.length > 0) {
            // 选择最安全的方向（距离玩家最远）
            const bestDirection = safeDirections.reduce((best, dir) => {
                const newPos = this.getNextPosition(aiHead, dir);
                const distance = this.getDistance(newPos, playerHead);
                return distance > best.distance ? {dir, distance} : best;
            }, {dir: safeDirections[0], distance: 0});
            
            this.aiSnake.direction = bestDirection.dir;
            return;
        }
        
        // 如果没有安全方向，使用随机移动
        this.randomMove(aiHead);
    }
    
    // 获取下一个位置
    getNextPosition(current, direction) {
        const newPos = {...current};
        switch(direction) {
            case 'up': newPos.y--; break;
            case 'down': newPos.y++; break;
            case 'left': newPos.x--; break;
            case 'right': newPos.x++; break;
        }
        return newPos;
    }
    
    // 检查方向是否安全
    isDirectionSafe(snake, direction) {
        const head = {...snake.body[0]};
        
        switch(direction) {
            case 'up': head.y--; break;
            case 'down': head.y++; break;
            case 'left': head.x--; break;
            case 'right': head.x++; break;
        }
        
        // 检查边界
        if (head.x < 0 || head.x >= this.game.gridWidth || head.y < 0 || head.y >= this.game.gridHeight) {
            return false;
        }
        
        // 检查蛇身（不包括尾巴）
        for (let i = 0; i < snake.body.length - 1; i++) {
            if (snake.body[i].x === head.x && snake.body[i].y === head.y) {
                return false;
            }
        }
        
        // 检查另一条蛇
        const otherSnake = snake === this.game.playerSnake ? this.aiSnake : this.game.playerSnake;
        for (let segment of otherSnake.body) {
            if (segment.x === head.x && segment.y === head.y) {
                return false;
            }
        }
        
        // 挑战模式下检查第二条AI蛇
        if (this.game.isChallengeMode && this.game.aiSnake2 && this.game.aiSnake2.isAlive) {
            // 如果是第一条AI蛇，检查第二条AI蛇
            if (snake === this.aiSnake) {
                for (let segment of this.game.aiSnake2.body) {
                    if (segment.x === head.x && segment.y === head.y) {
                        return false;
                    }
                }
            }
            // 如果是第二条AI蛇，检查第一条AI蛇
            else if (snake === this.game.aiSnake2) {
                for (let segment of this.aiSnake.body) {
                    if (segment.x === head.x && segment.y === head.y) {
                        return false;
                    }
                }
            }
        }
        
        return true;
    }
    
    // 寻找到食物的路径（改进版A*算法）
    findPathToFood(start) {
        if (!this.game.food) return null;
        
        const openSet = [{
            position: start,
            path: [start],
            gScore: 0,
            fScore: this.getDistance(start, this.game.food)
        }];
        
        const closedSet = new Set();
        
        while (openSet.length > 0) {
            // 按fScore排序，选择最优节点
            openSet.sort((a, b) => a.fScore - b.fScore);
            const current = openSet.shift();
            
            // 如果到达食物位置
            if (current.position.x === this.game.food.x && current.position.y === this.game.food.y) {
                return current.path;
            }
            
            closedSet.add(`${current.position.x},${current.position.y}`);
            
            // 检查四个方向
            const directions = [
                {x: 1, y: 0}, {x: -1, y: 0}, {x: 0, y: 1}, {x: 0, y: -1}
            ];
            
            for (const dir of directions) {
                const newPos = {
                    x: current.position.x + dir.x,
                    y: current.position.y + dir.y
                };
                
                const posKey = `${newPos.x},${newPos.y}`;
                
                // 检查是否已访问
                if (closedSet.has(posKey)) continue;
                
                // 检查位置是否有效
                if (newPos.x < 0 || newPos.x >= this.game.gridWidth || 
                    newPos.y < 0 || newPos.y >= this.game.gridHeight) {
                    continue;
                }
                
                // 检查是否与蛇身重叠
                let validPosition = true;
                for (let segment of this.aiSnake.body) {
                    if (segment.x === newPos.x && segment.y === newPos.y) {
                        validPosition = false;
                        break;
                    }
                }
                for (let segment of this.game.playerSnake.body) {
                    if (segment.x === newPos.x && segment.y === newPos.y) {
                        validPosition = false;
                        break;
                    }
                }
                
                if (!validPosition) continue;
                
                // 计算gScore和fScore
                const tentativeGScore = current.gScore + 1;
                const hScore = this.getDistance(newPos, this.game.food);
                const fScore = tentativeGScore + hScore;
                
                // 检查是否已在openSet中
                const existingNode = openSet.find(node => 
                    node.position.x === newPos.x && node.position.y === newPos.y
                );
                
                if (!existingNode) {
                    openSet.push({
                        position: newPos,
                        path: [...current.path, newPos],
                        gScore: tentativeGScore,
                        fScore: fScore
                    });
                } else if (tentativeGScore < existingNode.gScore) {
                    existingNode.path = [...current.path, newPos];
                    existingNode.gScore = tentativeGScore;
                    existingNode.fScore = fScore;
                }
            }
        }
        
        return null; // 没有找到路径
    }
    
    // 预测玩家移动方向
    predictPlayerDirection() {
        return this.game.playerSnake.direction;
    }
    
    // 预测玩家未来几步的位置
    predictPlayerPositions(steps) {
        const positions = [];
        let currentPos = {...this.game.playerSnake.body[0]};
        let currentDir = this.game.playerSnake.direction;
        
        for (let i = 0; i < steps; i++) {
            // 根据当前方向移动
            switch(currentDir) {
                case 'up': currentPos.y--; break;
                case 'down': currentPos.y++; break;
                case 'left': currentPos.x--; break;
                case 'right': currentPos.x++; break;
            }
            
            // 检查位置是否有效
            if (currentPos.x >= 0 && currentPos.x < this.game.gridWidth && 
                currentPos.y >= 0 && currentPos.y < this.game.gridHeight) {
                positions.push({...currentPos});
            } else {
                break;
            }
            
            // 模拟玩家可能改变方向（基于食物位置）
            if (this.game.food && Math.random() < 0.3) {
                const foodDir = this.getDirectionToTarget(currentPos, this.game.food);
                if (this.isDirectionSafe(this.game.playerSnake, foodDir)) {
                    currentDir = foodDir;
                }
            }
        }
        
        return positions;
    }
    
    // 计算最佳陷阱位置
    calculateOptimalTrapPosition(playerPos) {
        // 在玩家周围寻找合适的陷阱位置
        const directions = [
            {x: 1, y: 0}, {x: -1, y: 0}, {x: 0, y: 1}, {x: 0, y: -1},
            {x: 2, y: 0}, {x: -2, y: 0}, {x: 0, y: 2}, {x: 0, y: -2}
        ];
        
        const validPositions = [];
        
        for (const dir of directions) {
            const trapPos = {
                x: playerPos.x + dir.x,
                y: playerPos.y + dir.y
            };
            
            if (this.isTrapPositionValid(trapPos)) {
                validPositions.push(trapPos);
            }
        }
        
        // 选择距离AI最近的陷阱位置
        if (validPositions.length > 0) {
            const aiHead = this.aiSnake.body[0];
            return validPositions.reduce((best, pos) => {
                const distance = this.getDistance(aiHead, pos);
                return distance < best.distance ? {pos, distance} : best;
            }, {pos: validPositions[0], distance: Infinity}).pos;
        }
        
        return null;
    }
    
    // 检查陷阱位置是否有效
    isTrapPositionValid(pos) {
        // 检查边界
        if (pos.x < 0 || pos.x >= this.game.gridWidth || pos.y < 0 || pos.y >= this.game.gridHeight) {
            return false;
        }
        
        // 检查是否与蛇身重叠
        for (let segment of this.aiSnake.body) {
            if (segment.x === pos.x && segment.y === pos.y) {
                return false;
            }
        }
        for (let segment of this.game.playerSnake.body) {
            if (segment.x === pos.x && segment.y === pos.y) {
                return false;
            }
        }
        
        // 检查是否与食物重叠
        if (this.game.food && this.game.food.x === pos.x && this.game.food.y === pos.y) {
            return false;
        }
        if (this.game.goldenFood && this.game.goldenFood.x === pos.x && this.game.goldenFood.y === pos.y) {
            return false;
        }
        
        return true;
    }
    
    // 评估陷阱位置得分
    evaluateTrapPosition(trapPos, playerPos) {
        let score = 0;
        
        // 距离玩家越近得分越高
        const distanceToPlayer = this.getDistance(trapPos, playerPos);
        score += (10 - distanceToPlayer) * 2;
        
        // 距离AI越近得分越高
        const aiHead = this.aiSnake.body[0];
        const distanceToAI = this.getDistance(trapPos, aiHead);
        score += (10 - distanceToAI);
        
        // 陷阱位置的安全性（可到达性）
        const pathToTrap = this.findPathToPosition(aiHead, trapPos);
        if (pathToTrap) {
            score += 5;
        }
        
        return score;
    }
    
    // 寻找到指定位置的路径
    findPathToPosition(start, target) {
        const openSet = [{
            position: start,
            path: [start],
            gScore: 0,
            fScore: this.getDistance(start, target)
        }];
        
        const closedSet = new Set();
        
        while (openSet.length > 0) {
            openSet.sort((a, b) => a.fScore - b.fScore);
            const current = openSet.shift();
            
            if (current.position.x === target.x && current.position.y === target.y) {
                return current.path;
            }
            
            closedSet.add(`${current.position.x},${current.position.y}`);
            
            const directions = [
                {x: 1, y: 0}, {x: -1, y: 0}, {x: 0, y: 1}, {x: 0, y: -1}
            ];
            
            for (const dir of directions) {
                const newPos = {
                    x: current.position.x + dir.x,
                    y: current.position.y + dir.y
                };
                
                const posKey = `${newPos.x},${newPos.y}`;
                
                if (closedSet.has(posKey)) continue;
                
                if (newPos.x < 0 || newPos.x >= this.game.gridWidth || 
                    newPos.y < 0 || newPos.y >= this.game.gridHeight) {
                    continue;
                }
                
                let validPosition = true;
                for (let segment of this.aiSnake.body) {
                    if (segment.x === newPos.x && segment.y === newPos.y) {
                        validPosition = false;
                        break;
                    }
                }
                for (let segment of this.game.playerSnake.body) {
                    if (segment.x === newPos.x && segment.y === newPos.y) {
                        validPosition = false;
                        break;
                    }
                }
                
                if (!validPosition) continue;
                
                const tentativeGScore = current.gScore + 1;
                const hScore = this.getDistance(newPos, target);
                const fScore = tentativeGScore + hScore;
                
                const existingNode = openSet.find(node => 
                    node.position.x === newPos.x && node.position.y === newPos.y
                );
                
                if (!existingNode) {
                    openSet.push({
                        position: newPos,
                        path: [...current.path, newPos],
                        gScore: tentativeGScore,
                        fScore: fScore
                    });
                } else if (tentativeGScore < existingNode.gScore) {
                    existingNode.path = [...current.path, newPos];
                    existingNode.gScore = tentativeGScore;
                    existingNode.fScore = fScore;
                }
            }
        }
        
        return null;
    }
    
    // 计算陷阱位置
    calculateTrapPosition(playerHead, playerDirection) {
        const trapPos = {...playerHead};
        
        switch(playerDirection) {
            case 'up': trapPos.y -= 2; break;
            case 'down': trapPos.y += 2; break;
            case 'left': trapPos.x -= 2; break;
            case 'right': trapPos.x += 2; break;
        }
        
        // 检查陷阱位置是否有效
        if (trapPos.x >= 0 && trapPos.x < this.game.gridWidth && 
            trapPos.y >= 0 && trapPos.y < this.game.gridHeight) {
            return trapPos;
        }
        
        return null;
    }
    
    // 检查是否可以设置陷阱
    canSetTrap() {
        // 当AI蛇长度足够长且玩家距离适中时才能设置陷阱
        const playerHead = this.game.playerSnake.body[0];
        const aiHead = this.aiSnake.body[0];
        const distance = this.getDistance(aiHead, playerHead);
        
        return this.aiSnake.body.length > 5 && 
               distance >= 3 && distance <= 8 && 
               Math.random() < 0.6; // 提高陷阱设置概率
    }
    
    // 检查是否可以进入攻击模式
    checkAggressiveMode() {
        const aiLength = this.aiSnake.body.length;
        const currentTime = this.game.frameCount || 0;
        
        // 如果AI长度达到阈值且不在冷却期，进入攻击模式
        if (aiLength >= this.minLengthForAggressive && 
            currentTime - this.lastAggressiveTime >= this.aggressiveCooldown) {
            
            // 红色蛇有80%概率进入攻击模式，橙色蛇保持50%
            const isRedSnake = this.isSecondAI;
            const aggressiveChance = isRedSnake ? 0.8 : 0.5;
            
            if (Math.random() < aggressiveChance) {
                this.aggressiveMode = true;
                this.lastAggressiveTime = currentTime;
            }
        } else if (this.aggressiveMode) {
            // 攻击模式持续一段时间后自动退出
            // 红色蛇攻击模式持续时间更长（200帧），橙色蛇保持150帧
            const isRedSnake = this.isSecondAI;
            const aggressiveDuration = isRedSnake ? 200 : 150;
            
            if (currentTime - this.lastAggressiveTime >= aggressiveDuration) {
                this.aggressiveMode = false;
            }
        }
    }
    
    // 攻击性移动：尝试围困玩家或食物
    aggressiveMove(aiHead) {
        const playerHead = this.game.playerSnake.body[0];
        
        // 决定围困目标：玩家或食物
        let target;
        let targetType;
        
        // 红色蛇有90%概率围困玩家，橙色蛇保持70%概率围困玩家
        const isRedSnake = this.isSecondAI;
        const playerTargetChance = isRedSnake ? 0.9 : 0.7;
        
        if (Math.random() < playerTargetChance) {
            target = playerHead;
            targetType = 'player';
        } else {
            // 选择优先级最高的食物作为围困目标
            const foods = [];
            if (this.game.food) foods.push({type: 'normal', pos: this.game.food, priority: 1});
            if (this.game.food2) foods.push({type: 'normal2', pos: this.game.food2, priority: 1}); // 添加第二个食物
            if (this.game.goldenFood) foods.push({type: 'golden', pos: this.game.goldenFood, priority: 3});
            if (this.game.movingFood) foods.push({type: 'moving', pos: this.game.movingFood, priority: 4});
            
            if (foods.length > 0) {
                foods.sort((a, b) => b.priority - a.priority);
                target = foods[0].pos;
                targetType = 'food';
            } else {
                target = playerHead;
                targetType = 'player';
            }
        }
        
        // 计算围困位置（在目标周围寻找最佳位置）
        const siegePosition = this.calculateSiegePosition(target, targetType);
        
        if (siegePosition) {
            // 尝试移动到围困位置
            const direction = this.getDirectionToTarget(aiHead, siegePosition);
            if (this.isDirectionSafe(this.aiSnake, direction)) {
                this.aiSnake.direction = direction;
                return;
            }
        }
        
        // 如果围困失败，使用中等难度的移动策略
        this.mediumMove(aiHead);
    }
    
    // 计算围困位置
    calculateSiegePosition(target, targetType) {
        const directions = [
            {x: 1, y: 0}, {x: -1, y: 0}, {x: 0, y: 1}, {x: 0, y: -1},
            {x: 2, y: 0}, {x: -2, y: 0}, {x: 0, y: 2}, {x: 0, y: -2},
            {x: 1, y: 1}, {x: -1, y: 1}, {x: 1, y: -1}, {x: -1, y: -1}
        ];
        
        const validPositions = [];
        
        for (const dir of directions) {
            const siegePos = {
                x: target.x + dir.x,
                y: target.y + dir.y
            };
            
            // 检查位置是否有效
            if (this.isSiegePositionValid(siegePos, targetType)) {
                validPositions.push(siegePos);
            }
        }
        
        // 选择距离AI最近的围困位置
        if (validPositions.length > 0) {
            const aiHead = this.aiSnake.body[0];
            return validPositions.reduce((best, pos) => {
                const distance = this.getDistance(aiHead, pos);
                return distance < best.distance ? {pos, distance} : best;
            }, {pos: validPositions[0], distance: Infinity}).pos;
        }
        
        return null;
    }
    
    // 检查围困位置是否有效
    isSiegePositionValid(pos, targetType) {
        // 检查边界
        if (pos.x < 0 || pos.x >= this.game.gridWidth || pos.y < 0 || pos.y >= this.game.gridHeight) {
            return false;
        }
        
        // 检查是否与蛇身重叠
        for (let segment of this.aiSnake.body) {
            if (segment.x === pos.x && segment.y === pos.y) {
                return false;
            }
        }
        for (let segment of this.game.playerSnake.body) {
            if (segment.x === pos.x && segment.y === pos.y) {
                return false;
            }
        }
        
        // 如果是围困食物，不能与食物位置重叠
        if (targetType === 'food') {
            if (this.game.food && this.game.food.x === pos.x && this.game.food.y === pos.y) {
                return false;
            }
            if (this.game.goldenFood && this.game.goldenFood.x === pos.x && this.game.goldenFood.y === pos.y) {
                return false;
            }
            if (this.game.movingFood && this.game.movingFood.x === pos.x && this.game.movingFood.y === pos.y) {
                return false;
            }
        }
        
        return true;
    }
    
    // 检查是否与另一条AI蛇即将碰撞
    checkImminentCollisionWithOtherAI() {
        const aiHead = this.aiSnake.body[0];
        const otherAI = this.game.aiSnake2;
        
        if (!otherAI || !otherAI.isAlive) return false;
        
        const otherAIHead = otherAI.body[0];
        
        // 检查当前方向是否会与另一条AI蛇碰撞
        const currentDirection = this.aiSnake.direction;
        const nextPos = this.getNextPosition(aiHead, currentDirection);
        
        // 检查是否会与另一条AI蛇的头部碰撞（蛇头相撞）
        if (nextPos.x === otherAIHead.x && nextPos.y === otherAIHead.y) {
            return true;
        }
        
        // 检查是否会与另一条AI蛇的身体碰撞
        for (let i = 0; i < otherAI.body.length; i++) {
            if (nextPos.x === otherAI.body[i].x && nextPos.y === otherAI.body[i].y) {
                return true;
            }
        }
        
        // 检查另一条AI蛇是否会移动到当前位置（蛇头相撞）
        const otherNextPos = this.getNextPosition(otherAIHead, otherAI.direction);
        if (otherNextPos.x === aiHead.x && otherNextPos.y === aiHead.y) {
            return true;
        }
        
        return false;
    }
    
    // 避让移动：当与另一条AI蛇即将碰撞时，选择安全方向避让
    avoidCollisionMove(aiHead) {
        const directions = ['up', 'down', 'left', 'right'];
        const safeDirections = directions.filter(dir => 
            this.isDirectionSafe(this.aiSnake, dir)
        );
        
        if (safeDirections.length > 0) {
            // 优先选择能增加与另一条AI蛇距离的方向
            const otherAIHead = this.game.aiSnake2.body[0];
            const bestDirection = safeDirections.reduce((best, dir) => {
                const newPos = this.getNextPosition(aiHead, dir);
                const distance = this.getDistance(newPos, otherAIHead);
                return distance > best.distance ? {dir, distance} : best;
            }, {dir: safeDirections[0], distance: 0});
            
            this.aiSnake.direction = bestDirection.dir;
            return;
        }
        
        // 如果没有安全方向，使用随机移动
        this.randomMove(aiHead);
    }
    
    // 检查是否与另一条AI蛇抢同一个食物
    checkFoodCompetition() {
        const aiHead = this.aiSnake.body[0];
        const otherAI = this.game.aiSnake2;
        
        if (!otherAI || !otherAI.isAlive) return false;
        
        const otherAIHead = otherAI.body[0];
        
        // 检查所有食物的竞争情况
        const foods = [];
        if (this.game.food) foods.push(this.game.food);
        if (this.game.food2) foods.push(this.game.food2);
        if (this.game.goldenFood) foods.push(this.game.goldenFood);
        if (this.game.movingFood) foods.push(this.game.movingFood);
        
        // 检查是否有食物两条蛇距离相近（相差不超过1）
        for (const food of foods) {
            const aiDistance = this.getDistance(aiHead, food);
            const otherAIDistance = this.getDistance(otherAIHead, food);
            
            if (Math.abs(aiDistance - otherAIDistance) <= 1) {
                // 记录当前竞争的食物
                this.competingFood = food;
                return true;
            }
        }
        
        return false;
    }
    
    // 避让食物竞争：当与另一条AI蛇抢同一个食物时，选择其他食物
    avoidFoodCompetition(aiHead) {
        // 获取所有可用食物（排除当前竞争的食物）
        const availableFoods = this.getAllAvailableFoods(aiHead);
        
        // 排除当前竞争的食物
        const filteredFoods = availableFoods.filter(food => 
            food.position !== this.competingFood
        );
        
        // 如果没有其他食物，随机移动
        if (filteredFoods.length === 0) {
            this.randomMove(aiHead);
            return;
        }
        
        // 计算每个食物的综合得分
        filteredFoods.forEach(food => {
            const distanceScore = 10 - Math.min(food.distance, 10);
            
            // 黄色蛇（第一条AI蛇）更偏向高级食物，增加高级食物权重
            const isYellowSnake = !this.isSecondAI;
            let priorityMultiplier = 10;
            
            if (isYellowSnake) {
                // 黄色蛇对高级食物有更高偏好
                if (food.type === 'golden') priorityMultiplier = 15; // 金色食物权重更高
                else if (food.type === 'moving') priorityMultiplier = 20; // 移动食物权重最高
            }
            
            // 综合得分 = 优先级 * 权重 + 距离得分
            food.score = food.priority * priorityMultiplier + distanceScore;
        });
        
        // 按得分排序，选择得分最高的食物
        filteredFoods.sort((a, b) => b.score - a.score);
        
        // 尝试向得分最高的食物移动
        for (let i = 0; i < filteredFoods.length; i++) {
            const targetFood = filteredFoods[i];
            const direction = this.getDirectionToTarget(aiHead, targetFood.position);
            
            if (this.isDirectionSafe(this.aiSnake, direction)) {
                this.aiSnake.direction = direction;
                return;
            }
        }
        
        // 如果所有方向都不安全，使用随机移动
        this.randomMove(aiHead);
    }
    
    // 通讯机制移动：两条AI蛇协调食物分配
    communicatedMove(aiHead) {
        // 获取所有可用食物
        const availableFoods = this.getAllAvailableFoods(aiHead);
        
        // 如果没有食物，使用困难移动策略
        if (availableFoods.length === 0) {
            return this.hardMove(aiHead);
        }
        
        // 如果只有一个食物，两条蛇都向这个食物移动（不会碰撞死亡）
        if (availableFoods.length === 1) {
            const targetFood = availableFoods[0];
            const direction = this.getDirectionToTarget(aiHead, targetFood.position);
            
            if (this.isDirectionSafe(this.aiSnake, direction)) {
                this.aiSnake.direction = direction;
                return;
            }
        }
        
        // 如果有多个食物，实现食物分配通讯机制
        if (availableFoods.length > 1) {
            return this.coordinateFoodDistribution(aiHead, availableFoods);
        }
        
        // 默认使用困难移动策略
        return this.hardMove(aiHead);
    }
    
    // 获取所有可用食物
    getAllAvailableFoods(aiHead) {
        const availableFoods = [];
        
        // 第一个普通食物
        if (this.game.food) {
            availableFoods.push({
                type: 'normal',
                position: this.game.food,
                priority: 1,
                distance: this.getDistance(aiHead, this.game.food)
            });
        }
        
        // 第二个普通食物
        if (this.game.food2) {
            availableFoods.push({
                type: 'normal2',
                position: this.game.food2,
                priority: 1,
                distance: this.getDistance(aiHead, this.game.food2)
            });
        }
        
        // 金色食物
        if (this.game.goldenFood) {
            availableFoods.push({
                type: 'golden',
                position: this.game.goldenFood,
                priority: 3,
                distance: this.getDistance(aiHead, this.game.goldenFood)
            });
        }
        
        // 移动食物
        if (this.game.movingFood) {
            availableFoods.push({
                type: 'moving',
                position: this.game.movingFood,
                priority: 4,
                distance: this.getDistance(aiHead, this.game.movingFood)
            });
        }
        
        return availableFoods;
    }
    
    // 协调食物分配：当有多个食物时，根据距离分配食物，让AI蛇分开吃不同的食物
    coordinateFoodDistribution(aiHead, availableFoods) {
        const otherAI = this.game.aiSnake2;
        const otherAIHead = otherAI.body[0];
        
        // 计算每条蛇到每个食物的距离
        const foodAssignments = availableFoods.map(food => {
            const aiDistance = this.getDistance(aiHead, food.position);
            const otherAIDistance = this.getDistance(otherAIHead, food.position);
            
            return {
                food: food,
                aiDistance: aiDistance,
                otherAIDistance: otherAIDistance,
                distanceDifference: Math.abs(aiDistance - otherAIDistance)
            };
        });
        
        // 按距离差异排序，差异越小说明两条蛇距离差不多
        foodAssignments.sort((a, b) => a.distanceDifference - b.distanceDifference);
        
        // 检查是否有食物两条蛇距离差不多（差异小于等于2）
        const competitiveFoods = foodAssignments.filter(food => food.distanceDifference <= 2);
        
        if (competitiveFoods.length > 0) {
            // 有竞争食物，实现智能分配：让AI蛇分开吃不同的食物
            
            // 策略1：优先分配高级食物给黄色蛇
            const isYellowSnake = !this.isSecondAI;
            if (isYellowSnake) {
                // 黄色蛇优先选择高级食物
                const highPriorityFoods = availableFoods.filter(food => 
                    food.type === 'golden' || food.type === 'moving'
                );
                
                if (highPriorityFoods.length > 0) {
                    // 选择距离最近的高级食物
                    highPriorityFoods.sort((a, b) => a.distance - b.distance);
                    const targetFood = highPriorityFoods[0];
                    const direction = this.getDirectionToTarget(aiHead, targetFood.position);
                    
                    if (this.isDirectionSafe(this.aiSnake, direction)) {
                        this.aiSnake.direction = direction;
                        return;
                    }
                }
            } else {
                // 红色蛇优先选择普通食物，避免与黄色蛇竞争高级食物
                const normalFoods = availableFoods.filter(food => 
                    food.type === 'normal' || food.type === 'normal2'
                );
                
                if (normalFoods.length > 0) {
                    // 选择距离最近的普通食物
                    normalFoods.sort((a, b) => a.distance - b.distance);
                    const targetFood = normalFoods[0];
                    const direction = this.getDirectionToTarget(aiHead, targetFood.position);
                    
                    if (this.isDirectionSafe(this.aiSnake, direction)) {
                        this.aiSnake.direction = direction;
                        return;
                    }
                }
            }
            
            // 策略2：如果策略1失败，按更近的优先原则分配
            const competitiveFood = competitiveFoods[0];
            
            // 如果当前蛇更近，就选择这个食物
            if (competitiveFood.aiDistance <= competitiveFood.otherAIDistance) {
                const direction = this.getDirectionToTarget(aiHead, competitiveFood.food.position);
                if (this.isDirectionSafe(this.aiSnake, direction)) {
                    this.aiSnake.direction = direction;
                    return;
                }
            } else {
                // 如果另一条蛇更近，选择其他食物
                const otherFoods = availableFoods.filter(food => 
                    food.position !== competitiveFood.food.position
                );
                
                if (otherFoods.length > 0) {
                    // 选择距离最近的其他食物
                    otherFoods.sort((a, b) => a.distance - b.distance);
                    const targetFood = otherFoods[0];
                    const direction = this.getDirectionToTarget(aiHead, targetFood.position);
                    
                    if (this.isDirectionSafe(this.aiSnake, direction)) {
                        this.aiSnake.direction = direction;
                        return;
                    }
                }
            }
        }
        
        // 策略3：如果没有竞争食物，根据蛇的类型选择食物
        const isYellowSnake = !this.isSecondAI;
        
        if (isYellowSnake) {
            // 黄色蛇优先选择高级食物
            const highPriorityFoods = availableFoods.filter(food => 
                food.type === 'golden' || food.type === 'moving'
            );
            
            if (highPriorityFoods.length > 0) {
                highPriorityFoods.sort((a, b) => a.distance - b.distance);
                const targetFood = highPriorityFoods[0];
                const direction = this.getDirectionToTarget(aiHead, targetFood.position);
                
                if (this.isDirectionSafe(this.aiSnake, direction)) {
                    this.aiSnake.direction = direction;
                    return;
                }
            }
        }
        
        // 策略4：选择距离最近的食物
        availableFoods.sort((a, b) => a.distance - b.distance);
        const targetFood = availableFoods[0];
        const direction = this.getDirectionToTarget(aiHead, targetFood.position);
        
        if (this.isDirectionSafe(this.aiSnake, direction)) {
            this.aiSnake.direction = direction;
            return;
        }
        
        // 如果所有方向都不安全，使用困难移动策略
        return this.hardMove(aiHead);
    }
}